const app = getApp()
const request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        guid: wx.getStorageSync('guid'),
        authorization: wx.getStorageSync('token')
      },
      success(request) {
        if (request.data.Code === 200) {
          resolve(request.data)
        } else if (request.data.Code === 401) {
          resolve(request.data)
          wx.showModal({
            title: '请登录',
            content: '登录后才能进一步操作',
            confirmText: '去登录',
            cancelText: '不了',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/souquan/souquan',
                })
              } else if (res.cancel) {

              }
            }
          })
        }
        else {
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}

const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}

const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options
  })
}

const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}

module.exports = {
  get,
  post,
  put,
  remove
}